<?php
namespace App\V3\V3_2_7\Services;

use Illuminate\Support\Facades\DB;
use Illuminate\Support\Facades\Log;
use App\V3\V3_2_7\Models\SalesReturnGoodsDetailModel;
use App\V3\V3_2_7\Models\SalesReturnModel;
use App\V3\V3_2_7\Models\SalesReturnLogisticsInfoModel;
use App\V3\V3_2_7\Models\StorageManageModel;


class BarterReturnService
{
    //商品信息搜索
    static public function searchGoodsInfo($userId, $data)
    {
        $returnIdArr = [];
        $returnGoodsIdArr = [];
        
        $returnGoodsInfo = SalesReturnGoodsDetailModel::getBarterReturnGoodsDetailInfo($userId, $data);
        
        if(!empty($returnGoodsInfo)){
            $returnIdArr = array_unique(array_column($returnGoodsInfo, 'return_id'));
            $returnGoodsIdArr = array_unique(array_column($returnGoodsInfo, 'id'));
        }
        return self::commonSearchWithKeyword($userId, $data, $returnIdArr, $returnGoodsIdArr);
    }
    
    //根据请求参数搜索换货信息
    static public function searchBarterList($userId, $data)
    {
        $returnIdArr = [];
        $returnInfo = SalesReturnModel::getBarterReturnList($userId, $data);
        if(!empty($returnInfo)){
            $returnIdArr = array_unique(array_column($returnInfo, 'id'));
        }
        return self::commonSearchWithKeyword($userId, $data, $returnIdArr);
    }
    
    //快递单号检索
    static public function searchExpressNo($userId, $data)
    {
        $returnIdArr = [];
        $logisticsList = SalesReturnLogisticsInfoModel::getReturnLogisticsInfo($userId);
        if(!empty($logisticsList)){
            foreach ($logisticsList as $lVal){
                if(!empty($lVal['logistics_order_no'])){
                    $logisticsNoArr = explode(',', $lVal['logistics_order_no']);
                    if(!empty($logisticsNoArr)){
                        foreach ($logisticsNoArr as $nVal){
                            if(strpos($data['keyword'], $nVal) !== false){
                                $returnIdArr[] = $lVal['return_id'];
                            }
                        }
                    }
                }
            }
        }
        return self::commonSearchWithKeyword($userId, $data, array_unique($returnIdArr));
    }
    
    //搜索司机姓名
    static public function searchDriverName($userId, $data)
    {
        $returnIdArr = [];
        $driverList = BarterDriverModel::getBarterDriver($userId, $data);
        if(!empty($driverList)){
            $returnIdArr = array_unique(array_column($driverList, 'barter_id'));
        }
        
        return self::commonSearchWithKeyword($userId, $data, $returnIdArr);
    }
    
    //使用关键词检索
    static private function commonSearchWithKeyword($userId, $data, $returnIdArr = [], $returnGoodsIdArr=[])
    {
        if($data['user_id'] == $data['main_id']){
            $condition['a.main_id'] = ['EQ' => $data['main_id']];
        }else {
            $condition['a.user_id'] = ['EQ' => $data['user_id']];
        }
        $query = SalesReturnModel::select(
            'a.*',
            'b.username',
            'b.nickname',
            'a.id as return_id',
            'c.id as barter_id'
            )
            ->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->leftJoin('barter as c', 'c.barter_return_no', '=', 'a.barter_return_no')
            ->with('goodsDetailInfo', function($query) use($returnGoodsIdArr){
                $query->select(
                    'sales_return_goods_detail.id as return_goods_id',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img',
                    'price',
                    'sales_return_goods_detail.num',
                    'b.storage_name',
                    'b.id as storage_id',
                    'sales_return_goods_detail.materiel_type_id',
                    'sales_return_goods_detail.return_id',
                    'cost_price',
                    'sales_return_goods_detail.remark',
                    'sales_return_goods_detail.shelf_id',
                    'sales_return_goods_detail.location_id',
                    'se.shelf_name',
                    'lo.location_name',
                    'a.is_product_materiel'
                    )->where([
                        'se.status'=>1,
                        'lo.status'=>1,
                        'a.delete_flag'=>0,
                        'b.delete_flag'=>0,
                        'sales_return_goods_detail.delete_flag'=>0
                    ])
                    ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sales_return_goods_detail.warehouse_id')
                    ->leftJoin('storage_shelf as se','sales_return_goods_detail.shelf_id','=','se.id')
                    ->leftJoin('storage_shelf_location as lo','sales_return_goods_detail.location_id','=','lo.id');
                    if(!empty($barterGoodsIdArr)){
                        $query->whereIn('sales_return_goods_detail.id',$returnGoodsIdArr);
                    }
            })->where([
                'a.delete_flag'=>0,
                'a.repeal_status' => $data['repeal_status'],
                ['a.barter_return_no','!=','']
            ])->where($condition);
            
            if(!empty($data['start_time'])) {
                $startTimeArr = explode(' ', $data['start_time']);
                $startTime = strtotime($startTimeArr[0].' 00:00:00');
            }
            
            if(!empty($data['end_time'])) {
                $endTimeArr = explode(' ', $data['end_time']);
                $endTime = strtotime($endTimeArr[0].' 23:59:59');
            }
            
            if(!empty($startTime) && !empty($endTime)) {
                $query->whereBetween('refund_date', [$startTime, $endTime]);
            }
            else if(!empty($startTime) && empty($endTime)) {
                $query->where('refund_date', '>=', $startTime);
            }
            else if(empty($startTime) && !empty($endTime)) {
                $query->where('refund_date', '<=', $endTime);
            }
            //换货状态
            switch($data['status']) {
                //未收款未换货
                case 1:
                    $query->where('a.pay_status', 0);
                    $query->where('a.out_status', 0);
                    break;
                    //已收款
                case 2:
                    $query->where('a.pay_status', 0);
                    $query->where('a.out_status', 2);
                    break;
                    //已完结
                case 3:
                    $query->where('a.out_status', 2);
                    $query->where('a.pay_status', 2);
                    break;
            }
            $query = $query->whereIn('a.id', $returnIdArr)
            ->orderBy('a.id','desc');
            if(!empty($data['currentPage'])){
                
                $query = $query->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
                
            }else{
                $query = $query->toArray();
            }
            
            foreach($query['data'] as &$value) {
                foreach($value['goods_detail_info'] as $k => $val) {
                    $storageManageInfo = StorageManageModel::select('in_storage_num')
                    ->where([
                        'shelf_id'=>$val['shelf_id'],
                        'location_id'=>$val['location_id'],
                        'type_id'=>$val['materiel_type_id'],
                        'storage_id'=>$val['storage_id'],
                        'delete_flag'=>0
                    ])->first();
                    $value['goods_detail_info'][$k]['storage_manage_id'] = $storageManageInfo['id'];
                    $value['goods_detail_info'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                }
            }
            
            return $query;
    }
    
    static public function searchWithoutKeyword($userId, $data)
    {
        if($data['user_id'] == $data['main_id']){
            $condition['a.main_id'] = ['EQ' => $data['main_id']];
        }else {
            $condition['a.user_id'] = ['EQ' => $data['user_id']];
        }
        $query = SalesReturnModel::select(
            'a.*',
            'b.username',
            'b.nickname',
            'a.id as return_id',
            'c.id as barter_id'
            )->from('sales_return as a')
            ->leftJoin('admin as b', 'b.id', '=', 'a.user_id')
            ->leftJoin('barter as c', 'c.barter_return_no', '=', 'a.barter_return_no')
            ->with('goodsDetailInfo', function($query) {
                $query->select(
                    'sales_return_goods_detail.id as return_goods_id',
                    'a.materiel_name',
                    'a.type_name',
                    'a.materiel_no',
                    'a.materiel_img',
                    'price',
                    'sales_return_goods_detail.num',
                    'b.storage_name',
                    'b.id as storage_id',
                    'return_id',
                    'cost_price',
                    'sales_return_goods_detail.remark',
                    'sales_return_goods_detail.materiel_type_id',
                    'sales_return_goods_detail.shelf_id',
                    'sales_return_goods_detail.location_id',
                    'se.shelf_name',
                    'lo.location_name',
                    'a.is_product_materiel'
                    )->where([
                        'se.status'=>1,
                        'lo.status'=>1,
                        'a.delete_flag'=>0,
                        'b.delete_flag'=>0,
                        'sales_return_goods_detail.delete_flag'=>0
                    ])
                    ->leftJoin('materiel_type as a', 'a.id', '=', 'sales_return_goods_detail.materiel_type_id')
                    ->leftJoin('storage as b', 'b.id', '=', 'sales_return_goods_detail.warehouse_id')
                    ->leftJoin('storage_shelf as se','sales_return_goods_detail.shelf_id','=','se.id')
                    ->leftJoin('storage_shelf_location as lo','sales_return_goods_detail.location_id','=','lo.id');
            })->where([
                'a.delete_flag' =>0,
                'a.repeal_status' => $data['repeal_status'],
                ['a.barter_return_no','!=','']
            ])->where($condition);
            
            if(!empty($data['start_time'])) {
                $startTimeArr = explode(' ', $data['start_time']);
                $startTime = strtotime($startTimeArr[0].' 00:00:00');
            }
            
            if(!empty($data['end_time'])) {
                $endTimeArr = explode(' ', $data['end_time']);
                $endTime = strtotime($endTimeArr[0].' 23:59:59');
            }
            
            if(!empty($startTime) && !empty($endTime)) {
                $query->whereBetween('refund_date', [$startTime, $endTime]);
            }else if(!empty($startTime) && empty($endTime)) {
                $query->where('refund_date', '>=', $startTime);
            }else if(empty($startTime) && !empty($endTime)) {
                $query->where('refund_date', '<=', $endTime);
            }
            
            //销售单状态
            switch($data['status']) {
                //未收款未换货
                case 1:
                    $query->where('a.pay_status', 0);
                    $query->where('a.out_status', 0);
                    break;
                    //已收款
                case 2:
                    $query->where('a.pay_status', 0);
                    $query->where('a.out_status', 2);
                    break;
                    //已完结
                case 3:
                    $query->where('a.out_status', 2);
                    $query->where('a.pay_status', 2);
                    break;
            }
            if(!empty($data['currentPage'])){
                $query =  $query->orderBy('a.id','desc')->paginate($data['pageSize'],['*'], '',$data['currentPage'])->toArray();
            }else{
                $query = $query->orderBy('a.id','desc')->get()->toArray();
            }
            
            if(!empty($query['data'])){
                foreach($query['data'] as &$value) {
                    if(!empty($value['goods_detail_info'])){
                        foreach($value['goods_detail_info'] as $k => $val) {
                            $storageManageInfo = StorageManageModel::select('in_storage_num')
                            ->where([
                                'shelf_id'=>$val['shelf_id'],
                                'location_id'=>$val['location_id'],
                                'type_id'=>$val['materiel_type_id'],
                                'storage_id'=>$val['storage_id'],
                                'delete_flag'=>0
                            ])->first();
                            if(!empty($storageManageInfo)){
                                $value['goods_detail_info'][$k]['in_storage_num'] = $storageManageInfo['in_storage_num'];
                                
                            }else{
                                $value['goods_detail_info'][$k]['in_storage_num'] = 0;
                            }
                        }
                    }
                }
            }
            return $query;
    }
    
}
